<template>
  <div 
    class="modal" 
    @click.self="handleModalClick"
    @keydown.esc="handleClose"
    tabindex="0"
  >
    <div class="modal-content">
      <div class="modal-header">
        <h3>添加下载任务</h3>
        <button 
          class="close-btn" 
          @click="handleClose"
          :disabled="isSubmitting"
          aria-label="关闭"
        >
          ×
        </button>
      </div>
      
      <div class="modal-body">
        <!-- Error message -->
        <div v-if="error" class="error-message">
          <span class="error-icon">⚠️</span> {{ error }}
        </div>
        
        <!-- URL Input -->
        <div class="form-group">
          <label for="url">
            下载链接 <span class="required">*</span>
          </label>
          <div class="input-with-icon">
            <input 
              type="text" 
              id="url" 
              ref="urlInput"
              v-model="url" 
              placeholder="请输入下载链接 (支持 HTTP/HTTPS/磁力链)"
              @keyup.enter="handleSubmit"
              :disabled="isSubmitting"
              autofocus
            />
            <span class="input-icon">🔗</span>
          </div>
        </div>
        
        <!-- Save Path -->
        <div class="form-group">
          <label for="savePath">
            保存路径 <span class="required">*</span>
          </label>
          <div class="path-input">
            <div class="input-with-icon">
              <input 
                type="text" 
                id="savePath" 
                v-model="savePath" 
                placeholder="请选择保存路径"
                readonly
                :disabled="isSubmitting"
                @click="browseFolder"
              />
              <span class="input-icon">📁</span>
            </div>
            <button 
              class="browse-btn" 
              @click="browseFolder"
              :disabled="isSubmitting"
              :class="{ 'loading': isBrowsing }"
            >
              <span v-if="!isBrowsing">浏览</span>
              <span v-else class="spinner"></span>
            </button>
          </div>
          <p v-if="savePath" class="path-hint">
            将保存到: <span class="path">{{ savePath }}</span>
          </p>
        </div>
        
        <!-- Advanced Options (initially hidden) -->
        <div class="advanced-options">
          <button 
            class="toggle-options" 
            @click="showAdvanced = !showAdvanced"
            type="button"
          >
            {{ showAdvanced ? '隐藏' : '显示' }}高级选项
            <span class="arrow" :class="{ 'expanded': showAdvanced }">▼</span>
          </button>
          
          <transition name="slide">
            <div v-if="showAdvanced" class="options-content">
              <div class="form-group">
                <label for="fileName">
                  文件名 (可选)
                </label>
                <div class="input-with-icon">
                  <input 
                    type="text" 
                    id="fileName" 
                    v-model="fileName" 
                    placeholder="自定义下载文件名"
                    :disabled="isSubmitting"
                  />
                  <span class="input-icon">📝</span>
                </div>
              </div>
              
              <div class="form-group">
                <label for="category">
                  分类 (可选)
                </label>
                <div class="input-with-icon">
                  <input 
                    type="text" 
                    id="category" 
                    v-model="category" 
                    placeholder="输入分类名称"
                    :disabled="isLoading"
                  />
                  <span class="input-icon">🏷️</span>
                </div>
              </div>
            </div>
          </transition>
        </div>
        
        <!-- Form Actions -->
        <div class="form-actions">
          <button 
            class="btn btn-cancel" 
            @click="handleClose"
            :disabled="isSubmitting"
          >
            取消
          </button>
          <button 
            class="btn btn-submit" 
            @click="handleSubmit" 
            :disabled="!canSubmit"
            :class="{ 'loading': isSubmitting }"
          >
            <span v-if="!isSubmitting">开始下载</span>
            <span v-else class="spinner"></span>
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, defineProps, defineEmits, onMounted, nextTick } from 'vue';
import * as Manager from '../../wailsjs/go/main/Manager.js'

const props = defineProps({
  defaultPath: {
    type: String,
    default: ''
  }
});

const emit = defineEmits(['add', 'close']);

// Refs
const url = ref('');
const savePath = ref(props.defaultPath);
const fileName = ref('');
const category = ref('');
const error = ref('');
const isBrowsing = ref(false);
const isSubmitting = ref(false);
const showAdvanced = ref(false);
const urlInput = ref(null);

// Computed
const canSubmit = computed(() => {
  return url.value.trim() !== '' && 
         savePath.value.trim() !== '' && 
         !isBrowsing.value && 
         !isSubmitting.value;
});

// Methods
async function browseFolder() {
  if (isBrowsing.value) return
  isBrowsing.value = true
  error.value = ''

  try {
    const folderPath = await Manager.BrowseFolder()
    if (folderPath) {
      savePath.value = folderPath
    }
  } catch (err) {
    console.error('打开目录选择对话框失败:', err)
    error.value = `无法打开目录选择对话框: ${err.message || '未知错误'}`
  } finally {
    isBrowsing.value = false
  }
}

function validateForm() {
  // Reset error
  error.value = '';
  
  // Validate URL
  if (!url.value.trim()) {
    error.value = '请输入下载链接';
    return false;
  }
  
  // Basic URL validation (supports magnet links)
  if (!url.value.startsWith('magnet:') && !url.value.startsWith('http')) {
    error.value = '请输入有效的下载链接 (支持 HTTP/HTTPS/磁力链)';
    return false;
  }
  
  // Validate save path
  if (!savePath.value.trim()) {
    error.value = '请选择保存路径';
    return false;
  }
  
  return true;
}

async function handleSubmit() {
  if (!validateForm()) return;
  
  isSubmitting.value = true;
  
  try {
    emit('add', {
      url: url.value.trim(),
      path: savePath.value,
      fileName: fileName.value.trim(),
      category: category.value.trim()
    });
    
    // Reset form
    resetForm();
    emit('close');
  } catch (err) {
    console.error('Error adding download:', err);
    error.value = '添加下载任务失败: ' + (err.message || '未知错误');
  } finally {
    isSubmitting.value = false;
  }
}

function resetForm() {
  url.value = '';
  fileName.value = '';
  category.value = '';
  error.value = '';
}

function handleClose() {
  if (!isSubmitting.value) {
    emit('close');
  }
}

function handleModalClick() {
  // Focus URL input when clicking on modal background
  if (urlInput.value) {
    urlInput.value.focus();
  }
}

// Lifecycle
onMounted(async () => {
  // Ask backend for accurate default Downloads directory when none provided
  try {
    if (!savePath.value) {
      const dir = await Manager.GetDefaultDownloadDir()
      if (dir) savePath.value = dir
    }
  } catch (e) {
    // noop: keep empty and let user browse
  }

  // Auto-focus URL input when modal opens
  if (urlInput.value) {
    urlInput.value.focus();
  }
});
</script>

<style scoped>
/* Base Modal Styles */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  backdrop-filter: blur(2px);
  animation: fadeIn 0.2s ease-out;
  padding: 20px;
  outline: none;
}

@keyframes fadeIn {
  from { opacity: 0; backdrop-filter: blur(0); }
  to { opacity: 1; backdrop-filter: blur(2px); }
}

.modal-content {
  background-color: var(--card-bg);
  border-radius: 12px;
  width: 100%;
  max-width: 520px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
  overflow: hidden;
  transform: translateY(20px);
  opacity: 0;
  animation: slideUp 0.3s ease-out 0.1s forwards;
  border: 1px solid var(--border-color);
  max-height: 90vh;
  display: flex;
  flex-direction: column;
}

@keyframes slideUp {
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

.modal-header {
  padding: 18px 24px;
  border-bottom: 1px solid var(--border-color);
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: var(--bg-color);
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: var(--text-color);
  display: flex;
  align-items: center;
  gap: 8px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: var(--text-secondary);
  padding: 4px 8px;
  line-height: 1;
  border-radius: 4px;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
}

.close-btn:hover:not(:disabled) {
  background-color: rgba(255, 255, 255, 0.1);
  color: var(--text-color);
}

.close-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.modal-body {
  padding: 24px;
  overflow-y: auto;
  flex: 1;
}

/* Form Styles */
.form-group {
  margin-bottom: 20px;
  position: relative;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: var(--text-color);
  font-size: 14px;
}

.required {
  color: #ff4d4f;
  margin-left: 4px;
}

.input-with-icon {
  position: relative;
  display: flex;
  align-items: center;
}

.input-with-icon .input-icon {
  position: absolute;
  left: 12px;
  color: var(--text-secondary);
  pointer-events: none;
}

.input-with-icon input {
  padding-left: 40px !important;
  width: 100%;
  padding: 10px 16px 10px 40px;
  border: 1px solid var(--border-color);
  border-radius: 6px;
  background-color: var(--input-bg, var(--bg-color));
  color: var(--text-color);
  font-size: 14px;
  transition: all 0.2s;
  height: 42px;
}

.input-with-icon input:focus {
  border-color: var(--primary-color);
  box-shadow: 0 0 0 2px rgba(66, 165, 245, 0.2);
  outline: none;
}

.input-with-icon input:disabled {
  background-color: rgba(255, 255, 255, 0.05);
  cursor: not-allowed;
  opacity: 0.7;
}

.path-input {
  display: flex;
  gap: 8px;
  align-items: center;
}

.path-input .input-with-icon {
  flex: 1;
}

.path-hint {
  margin: 6px 0 0;
  font-size: 12px;
  color: var(--text-secondary);
  word-break: break-all;
  line-height: 1.4;
}

.path-hint .path {
  color: var(--primary-color);
  font-family: monospace;
  background: rgba(66, 165, 245, 0.1);
  padding: 1px 4px;
  border-radius: 3px;
}

.browse-btn {
  padding: 0 16px;
  height: 42px;
  background-color: var(--primary-color);
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  white-space: nowrap;
  transition: all 0.2s;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-width: 80px;
}

.browse-btn:hover:not(:disabled) {
  background-color: var(--primary-dark);
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.browse-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* Error Message */
.error-message {
  background-color: rgba(255, 77, 79, 0.1);
  color: #ff4d4f;
  padding: 10px 16px;
  border-radius: 6px;
  margin-bottom: 20px;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 8px;
  border: 1px solid rgba(255, 77, 79, 0.2);
  animation: shake 0.5s ease-in-out;
}

@keyframes shake {
  0%, 100% { transform: translateX(0); }
  10%, 30%, 50%, 70%, 90% { transform: translateX(-2px); }
  20%, 40%, 60%, 80% { transform: translateX(2px); }
}

.error-icon {
  font-size: 16px;
}

/* Advanced Options */
.advanced-options {
  margin: 24px 0;
  border: 1px solid var(--border-color);
  border-radius: 8px;
  overflow: hidden;
}

.toggle-options {
  width: 100%;
  padding: 12px 16px;
  background: var(--bg-color);
  border: none;
  color: var(--primary-color);
  font-size: 13px;
  font-weight: 500;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: space-between;
  transition: all 0.2s;
}

.toggle-options:hover {
  background: rgba(255, 255, 255, 0.05);
}

.toggle-options .arrow {
  transition: transform 0.2s;
  font-size: 10px;
  opacity: 0.7;
}

.toggle-options .arrow.expanded {
  transform: rotate(180deg);
}

.options-content {
  padding: 16px;
  background: rgba(255, 255, 255, 0.02);
  border-top: 1px solid var(--border-color);
}

/* Form Actions */
.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
  padding-top: 20px;
  border-top: 1px solid var(--border-color);
}

.btn {
  padding: 0 20px;
  height: 40px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-width: 100px;
}

.btn-cancel {
  background-color: transparent;
  border: 1px solid var(--border-color);
  color: var(--text-color);
}

.btn-cancel:hover:not(:disabled) {
  background-color: rgba(255, 255, 255, 0.05);
  border-color: var(--border-color);
}

.btn-submit {
  background-color: var(--primary-color);
  color: white;
  border: 1px solid var(--primary-color);
  font-weight: 500;
}

.btn-submit:hover:not(:disabled) {
  background-color: var(--primary-dark);
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none !important;
  box-shadow: none !important;
}

/* Loading Spinner */
.spinner {
  display: inline-block;
  width: 16px;
  height: 16px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  border-top-color: #fff;
  animation: spin 0.8s ease-in-out infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* Transitions */
.slide-enter-active, .slide-leave-active {
  transition: all 0.3s ease;
  max-height: 500px;
  overflow: hidden;
}

.slide-enter-from, .slide-leave-to {
  opacity: 0;
  max-height: 0;
  margin: 0;
  padding: 0;
  border: none;
}

/* Responsive */
@media (max-width: 480px) {
  .modal-content {
    max-width: 100%;
    border-radius: 0;
    height: 100%;
    max-height: 100%;
  }
  
  .form-actions {
    flex-direction: column;
  }
  
  .btn {
    width: 100%;
  }
}
</style>
